﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using WCYCReader.Main;
using WCYCReader.Main.Core;
using WCYCReader.Models;
using WCYCReader.Utility;
using WCYCReader.ViewModels;

namespace WCYCReader.Pages
{
    public partial class BookSearchRankPage : PhoneApplicationPage
    {
        protected PerformanceProgressBar HotComprehensiveProgressBar = new PerformanceProgressBar();

        protected PerformanceProgressBar NewOriginalProgressBar = new PerformanceProgressBar();

        protected PerformanceProgressBar NewPublishingProgressBar = new PerformanceProgressBar();

        protected HotComprehensiveBookList_VM hcbl_vm = new HotComprehensiveBookList_VM();

        protected NewOriginalBookList_VM nobl_vm = new NewOriginalBookList_VM();

        protected NewPublishingBookList_VM npbl_vm = new NewPublishingBookList_VM();

        protected bool HotComprehensiveLoading;

        protected bool NewOriginalLoading;

        protected bool NewPublishingLoading;

        protected PerformanceProgressBar BoyProgressBar = new PerformanceProgressBar();

        protected PerformanceProgressBar GirlProgressBar = new PerformanceProgressBar();

        protected GirlBookList_VM gbl_vm = new GirlBookList_VM();

        protected BoyBookList_VM bbl_vm = new BoyBookList_VM();

        protected bool BoyLoading;

        protected bool GirlLoading;

        public BookSearchRankPage()
        {
            InitializeComponent();
            //
            //this.AddHeaderToPivotItem();
        }

        /// <summary>
        /// 添加标题至PivotItem
        /// <para>因为代码中的多个PivotItem只能包含一个phone:PivotItem.Header控件</para>
        /// </summary>
        private void AddHeaderToPivotItem()
        {
            //<TextBlock Margin="-20,-15,0,0" Foreground="#c1dc23" FontSize="60" Text="详细信息"/>
            //this.piAll.Header = new PivotItemHelper().CreateTextBlock("书城综合榜");
            this.piPublishNew.Header = new PivotItemHelper().CreateTextBlock("出版新书榜");
            this.piWriteNew.Header = new PivotItemHelper().CreateTextBlock("原创新书榜");
            this.piBoy.Header = new PivotItemHelper().CreateTextBlock("男生排行榜");
            this.piGirl.Header = new PivotItemHelper().CreateTextBlock("女生排行榜");
        }


        protected void AddPerformanceProgressBar(QQRankPageProgressBar pro)
        {
            switch (pro)
            {
                case QQRankPageProgressBar.HotComprehensivePro:
                    {
                        if (this.HotComprehensiveProgressBar.IsIndeterminate)
                        {
                            break;
                        }
                        this.HotComprehensiveProgressBar.IsIndeterminate = true;
                        this.HotComprehensiveProgressBar.Foreground = new SolidColorBrush(Colors.Red);
                        this.HotComprehensiveProgressBar.Height = 20;
                        this.RemovePerformanceProgressBar(this.NewOriginalProgressBar);
                        this.RemovePerformanceProgressBar(this.NewPublishingProgressBar);
                        return;
                    }
                case QQRankPageProgressBar.NewOriginalPro:
                    {
                        if (this.NewOriginalProgressBar.IsIndeterminate)
                        {
                            break;
                        }
                        this.NewOriginalProgressBar.IsIndeterminate = true;
                        this.NewOriginalProgressBar.Foreground = new SolidColorBrush(Colors.Red);
                        this.NewOriginalProgressBar.Height = 20;
                        this.RemovePerformanceProgressBar(this.HotComprehensiveProgressBar);
                        this.RemovePerformanceProgressBar(this.NewPublishingProgressBar);
                        return;
                    }
                case QQRankPageProgressBar.NewPublishingPro:
                    {
                        if (this.NewPublishingProgressBar.IsIndeterminate)
                        {
                            break;
                        }
                        this.NewPublishingProgressBar.IsIndeterminate = true;
                        this.NewPublishingProgressBar.Foreground = new SolidColorBrush(Colors.Red);
                        this.NewPublishingProgressBar.Height = 20;
                        this.RemovePerformanceProgressBar(this.HotComprehensiveProgressBar);
                        this.RemovePerformanceProgressBar(this.NewOriginalProgressBar);
                        return;
                    }
                default:
                    {
                        this.RemovePerformanceProgressBar(this.HotComprehensiveProgressBar);
                        this.RemovePerformanceProgressBar(this.NewPublishingProgressBar);
                        this.RemovePerformanceProgressBar(this.NewOriginalProgressBar);
                        break;
                    }
            }
        }


        private void ContentGrid_Loaded(object sender, RoutedEventArgs e)
        {
            //this.hotComprehensiveBookListBox.ItemsSource = this.hcbl_vm.T_HotComprehensiveBookList_VM();
            this.newOriginalBookListBox.ItemsSource = this.nobl_vm.T_NewOriginalBookList_VM();
            this.newPublishingBookListBox.ItemsSource = this.npbl_vm.T_NewPublishingBookList_VM();
            this.LayoutRoot.Children.Add(this.NewPublishingProgressBar);
            //this.LayoutRoot.Children.Add(this.HotComprehensiveProgressBar);
            this.LayoutRoot.Children.Add(this.NewOriginalProgressBar);
            //
            this.boyBookListBox.ItemsSource = this.bbl_vm.T_BoyBookList_VM();
            this.girlBookListBox.ItemsSource = this.gbl_vm.T_GirlBookList_VM();
            this.LayoutRoot.Children.Add(this.GirlProgressBar);
            this.LayoutRoot.Children.Add(this.BoyProgressBar);
        }

        private void ContentGrid_Unloaded(object sender, RoutedEventArgs e)
        {
            this.AddPerformanceProgressBar(QQRankPageProgressBar.RemoveAll);
            this.LayoutRoot.Children.Remove(this.NewPublishingProgressBar);
            //this.LayoutRoot.Children.Remove(this.HotComprehensiveProgressBar);
            this.LayoutRoot.Children.Remove(this.NewOriginalProgressBar);
            //
            this.AddPerformanceProgressBarToBoyAndGrid(QQRecommendPageProgressBar.RemoveAll);
            this.LayoutRoot.Children.Remove(this.GirlProgressBar);
            this.LayoutRoot.Children.Remove(this.BoyProgressBar);
        }

        private void hotComprehensiveBook_DownloadStringCompleted(object sender, WCYCReader.Main.Core.DownloadStringCompletedEventArgs e)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                if (e.Result != null)
                {
                    JsonData jsonDatum = new JsonData();
                    jsonDatum = ParseJson.Parse<JsonData>(e.Result);
                    this.hcbl_vm.SetHotComprehensiveBookList(jsonDatum);
                }
                else
                {
                    Prompt.PromptMessage("提示：网络异常！");
                }
                this.HotComprehensiveLoading = false;
                this.RemovePerformanceProgressBar(this.HotComprehensiveProgressBar);
            });
        }

        private void hotComprehensiveBookListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListBox listBox = sender as ListBox;
            if (listBox.SelectedIndex >= 0)
            {
                SettingHelper.SaveInToSettings("BookDetail", this.hcbl_vm.T_HotComprehensiveBookList_VM()[listBox.SelectedIndex]);
                NaviService.Navigate(QQReaderPage.EBookDetailPage, "");
            }
            listBox.SelectedIndex = -1;
        }



        private void newOriginalBook_DownloadStringCompleted(object sender, WCYCReader.Main.Core.DownloadStringCompletedEventArgs e)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                if (e.Result != null)
                {
                    JsonData jsonDatum = new JsonData();
                    jsonDatum = ParseJson.Parse<JsonData>(e.Result);
                    this.nobl_vm.SetNewOriginalBookList(jsonDatum);
                }
                else
                {
                    Prompt.PromptMessage("提示：网络异常！");
                }
                this.NewOriginalLoading = false;
                this.RemovePerformanceProgressBar(this.NewOriginalProgressBar);
            });
        }

        private void newOriginalBookListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListBox listBox = sender as ListBox;
            if (listBox.SelectedIndex >= 0)
            {
                SettingHelper.SaveInToSettings("BookDetail", this.nobl_vm.T_NewOriginalBookList_VM()[listBox.SelectedIndex]);
                NaviService.Navigate(QQReaderPage.EBookDetailPage, "");
            }
            listBox.SelectedIndex = -1;
        }

        private void newPublishingBook_DownloadStringCompleted(object sender, WCYCReader.Main.Core.DownloadStringCompletedEventArgs e)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                if (e.Result != null)
                {
                    JsonData jsonDatum = new JsonData();
                    jsonDatum = ParseJson.Parse<JsonData>(e.Result);
                    this.npbl_vm.SetNewPublishingBookList(jsonDatum);
                }
                else
                {
                    Prompt.PromptMessage("提示：网络异常！");
                }
                this.NewPublishingLoading = false;
                this.RemovePerformanceProgressBar(this.NewPublishingProgressBar);
            });
        }

        private void newPublishingBookListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListBox listBox = sender as ListBox;
            if (listBox.SelectedIndex >= 0)
            {
                SettingHelper.SaveInToSettings("BookDetail", this.npbl_vm.T_NewPublishingBookList_VM()[listBox.SelectedIndex]);
                NaviService.Navigate(QQReaderPage.EBookDetailPage, "");
            }
            listBox.SelectedIndex = -1;
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            //
            //App.QQReader_prePageId = App.QQReader_pageId;
            //App.QQReader_pageId = "QQReader_RankPage_type0";
            //if (this.hcbl_vm.T_HotComprehensiveBookList_VM().Count == 0 && !this.HotComprehensiveLoading)
            //{
            //    this.AddPerformanceProgressBar(QQRankPageProgressBar.HotComprehensivePro);
            //    this.HotComprehensiveLoading = true;
            //    Dictionary<string, string> strs = new Dictionary<string, string>()
            //    {
            //        { "type", "0" },
            //        { "pageSize", "20" },
            //        { "fromWho", "4" }
            //    };
            //    HttpPostClient httpPostClient = new HttpPostClient(strs, GetHttpInfo.GetHttpHeaders());
            //    httpPostClient.DownloadStringAsync(new Uri("http://appassist.3g.qq.com/rank/rank", UriKind.Absolute));
            //    httpPostClient.DownloadStringCompleted += new HttpPostClient.DownloadStringCompletedHandler(this.hotComprehensiveBook_DownloadStringCompleted);
            //}
            //
            App.QQReader_prePageId = App.QQReader_pageId;
            App.QQReader_pageId = "QQReader_RankPage_type1";
            if ( this.npbl_vm.T_NewPublishingBookList_VM().Count == 0 && !this.NewPublishingLoading)
            {
                App.QQReader_prePageId = App.QQReader_pageId;
                App.QQReader_pageId = "QQReader_RankPage_type1";
                this.AddPerformanceProgressBar(QQRankPageProgressBar.NewPublishingPro);
                this.NewPublishingLoading = true;
                Dictionary<string, string> strs = new Dictionary<string, string>()
                {
                    { "type", "1" },
                    { "pageSize", "20" },
                    { "fromWho", "4" }
                };
                HttpPostClient httpPostClient = new HttpPostClient(strs, GetHttpInfo.GetHttpHeaders());
                httpPostClient.DownloadStringAsync(new Uri("http://appassist.3g.qq.com/rank/new", UriKind.Absolute));
                httpPostClient.DownloadStringCompleted += new HttpPostClient.DownloadStringCompletedHandler(this.newPublishingBook_DownloadStringCompleted);
                return;
            }
            //
            App.QQReader_prePageId = App.QQReader_pageId;
            App.QQReader_pageId = "QQReader_RecommendPage_type2";
            if (this.bbl_vm.T_BoyBookList_VM().Count == 0 && !this.BoyLoading)
            {
                this.AddPerformanceProgressBarToBoyAndGrid(QQRecommendPageProgressBar.BoyPro);
                this.BoyLoading = true;
                Dictionary<string, string> strs = new Dictionary<string, string>()
                {
                    { "type", "2" },
                    { "pageSize", "20" },
                    { "fromWho", "4" }
                };
                HttpPostClient httpPostClient = new HttpPostClient(strs, GetHttpInfo.GetHttpHeaders());
                httpPostClient.DownloadStringAsync(new Uri("http://appassist.3g.qq.com/rank/levelOne", UriKind.Absolute));
                httpPostClient.DownloadStringCompleted += new HttpPostClient.DownloadStringCompletedHandler(this.boyBook_DownloadStringCompleted);
            }
        }

        protected void RemovePerformanceProgressBar(PerformanceProgressBar pro)
        {
            if (pro.IsIndeterminate)
            {
                pro.IsIndeterminate = false;
            }
        }

        private void pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //发布新版
            if (this.piPublishNew == this.pivot.SelectedItem && this.npbl_vm.T_NewPublishingBookList_VM().Count == 0 && !this.NewPublishingLoading)
            {
                App.QQReader_prePageId = App.QQReader_pageId;
                App.QQReader_pageId = "QQReader_RankPage_type1";
                this.AddPerformanceProgressBar(QQRankPageProgressBar.NewPublishingPro);
                this.NewPublishingLoading = true;
                Dictionary<string, string> strs = new Dictionary<string, string>()
                {
                    { "type", "1" },
                    { "pageSize", "20" },
                    { "fromWho", "4" }
                };
                HttpPostClient httpPostClient = new HttpPostClient(strs, GetHttpInfo.GetHttpHeaders());
                httpPostClient.DownloadStringAsync(new Uri("http://appassist.3g.qq.com/rank/new", UriKind.Absolute));
                httpPostClient.DownloadStringCompleted += new HttpPostClient.DownloadStringCompletedHandler(this.newPublishingBook_DownloadStringCompleted);
                return;
            }
            //原创新版
            if (this.piWriteNew == this.pivot.SelectedItem && this.nobl_vm.T_NewOriginalBookList_VM().Count == 0 && !this.NewOriginalLoading)
            {
                App.QQReader_prePageId = App.QQReader_pageId;
                App.QQReader_pageId = "QQReader_RankPage_type2";
                this.AddPerformanceProgressBar(QQRankPageProgressBar.NewOriginalPro);
                this.NewOriginalLoading = true;
                Dictionary<string, string> strs1 = new Dictionary<string, string>()
                {
                    { "type", "0" },
                    { "pageSize", "20" },
                    { "fromWho", "4" }
                };
                HttpPostClient httpPostClient1 = new HttpPostClient(strs1, GetHttpInfo.GetHttpHeaders());
                httpPostClient1.DownloadStringAsync(new Uri("http://appassist.3g.qq.com/rank/new", UriKind.Absolute));
                httpPostClient1.DownloadStringCompleted += new HttpPostClient.DownloadStringCompletedHandler(this.newOriginalBook_DownloadStringCompleted);
            }
            //
            if (this.piGirl == this.pivot.SelectedItem && this.gbl_vm.T_GirlBookList_VM().Count == 0 && !this.GirlLoading)
            {
                App.QQReader_prePageId = App.QQReader_pageId;
                App.QQReader_pageId = "QQReader_RecommendPage_type3";
                this.AddPerformanceProgressBarToBoyAndGrid(QQRecommendPageProgressBar.GirlPro);
                this.GirlLoading = true;
                Dictionary<string, string> strs = new Dictionary<string, string>()
                {
                    { "type", "3" },
                    { "pageSize", "20" },
                    { "fromWho", "4" }
                };
                HttpPostClient httpPostClient = new HttpPostClient(strs, GetHttpInfo.GetHttpHeaders());
                httpPostClient.DownloadStringAsync(new Uri("http://appassist.3g.qq.com/rank/levelOne", UriKind.Absolute));
                httpPostClient.DownloadStringCompleted += new HttpPostClient.DownloadStringCompletedHandler(this.girlBook_DownloadStringCompleted);
            }

            if (this.piBoy == this.pivot.SelectedItem && this.bbl_vm.T_BoyBookList_VM().Count == 0 && !this.BoyLoading)
            {
                this.AddPerformanceProgressBarToBoyAndGrid(QQRecommendPageProgressBar.BoyPro);
                this.BoyLoading = true;
                Dictionary<string, string> strs = new Dictionary<string, string>()
                {
                    { "type", "2" },
                    { "pageSize", "20" },
                    { "fromWho", "4" }
                };
                HttpPostClient httpPostClient = new HttpPostClient(strs, GetHttpInfo.GetHttpHeaders());
                httpPostClient.DownloadStringAsync(new Uri("http://appassist.3g.qq.com/rank/levelOne", UriKind.Absolute));
                httpPostClient.DownloadStringCompleted += new HttpPostClient.DownloadStringCompletedHandler(this.boyBook_DownloadStringCompleted);
            }
        }


        #region 男生女生榜单
        protected void AddPerformanceProgressBarToBoyAndGrid(QQRecommendPageProgressBar pro)
        {
            switch (pro)
            {
                case QQRecommendPageProgressBar.BoyPro:
                    {
                        if (this.BoyProgressBar.IsIndeterminate)
                        {
                            break;
                        }
                        this.BoyProgressBar.IsIndeterminate = true;
                        this.BoyProgressBar.Height = 20;
                        this.BoyProgressBar.Foreground = new SolidColorBrush(Colors.Red);
                        this.RemovePerformanceProgressBarToBoyAndGrid(this.GirlProgressBar);
                        return;
                    }
                case QQRecommendPageProgressBar.GirlPro:
                    {
                        if (this.GirlProgressBar.IsIndeterminate)
                        {
                            break;
                        }
                        this.GirlProgressBar.IsIndeterminate = true;
                        this.GirlProgressBar.Height = 20;
                        this.GirlProgressBar.Foreground = new SolidColorBrush(Colors.Red);
                        this.RemovePerformanceProgressBar(this.BoyProgressBar);
                        return;
                    }
                default:
                    {
                        this.RemovePerformanceProgressBarToBoyAndGrid(this.BoyProgressBar);
                        this.RemovePerformanceProgressBarToBoyAndGrid(this.GirlProgressBar);
                        break;
                    }
            }
        }



        private void boyBook_DownloadStringCompleted(object sender, WCYCReader.Main.Core.DownloadStringCompletedEventArgs e)
        {
            base.Dispatcher.BeginInvoke(() =>
            {
                if (e.Result != null)
                {
                    JsonData jsonDatum = new JsonData();
                    jsonDatum = ParseJson.Parse<JsonData>(e.Result);
                    this.bbl_vm.SetBoyBookList(jsonDatum);
                }
                else
                {
                    Prompt.PromptMessage("提示：网络异常！");
                }
                this.BoyLoading = false;
                this.RemovePerformanceProgressBar(this.BoyProgressBar);
            });
        }

        private void boyBookListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListBox listBox = sender as ListBox;
            if (listBox.SelectedIndex >= 0)
            {
                SettingHelper.SaveInToSettings("BookDetail", this.bbl_vm.T_BoyBookList_VM()[listBox.SelectedIndex]);
                NaviService.Navigate(QQReaderPage.EBookDetailPage, "");
            }
            listBox.SelectedIndex = -1;
        }

        

        private void girlBook_DownloadStringCompleted(object sender, WCYCReader.Main.Core.DownloadStringCompletedEventArgs e)
        {
            base.Dispatcher.BeginInvoke(() =>
            {
                if (e.Result != null)
                {
                    JsonData jsonDatum = new JsonData();
                    jsonDatum = ParseJson.Parse<JsonData>(e.Result);
                    this.gbl_vm.SetGirlBookList(jsonDatum);
                }
                else
                {
                    Prompt.PromptMessage("提示：网络异常！");
                }
                this.GirlLoading = false;
                this.RemovePerformanceProgressBarToBoyAndGrid(this.GirlProgressBar);
            });
        }

        private void girlBookListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListBox listBox = sender as ListBox;
            if (listBox.SelectedIndex >= 0)
            {
                SettingHelper.SaveInToSettings("BookDetail", this.gbl_vm.T_GirlBookList_VM()[listBox.SelectedIndex]);
                NaviService.Navigate(QQReaderPage.EBookDetailPage, "");
            }
            listBox.SelectedIndex = -1;
        }


        protected void RemovePerformanceProgressBarToBoyAndGrid(PerformanceProgressBar pro)
        {
            if (pro.IsIndeterminate)
            {
                pro.IsIndeterminate = false;
            }
        }
        #endregion 男生女生榜单

    }
}